/*
Source : https://leetcode.com/problems/contains-duplicate-ii/
Author : nflush@outlook.com
Date   : 2016-07-05
*/

/*
219. Contains Duplicate II

    Total Accepted: 65153
    Total Submissions: 213844
    Difficulty: Easy

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

Subscribe to see which companies asked this question
*/
// tle
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        for (int j = k; j >0; j--)
            for (int i = j; i < nums.size(); i++)
                if (nums[i] == nums[i-j])
                    return true;

        return false;
    }
};


class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (int i=0; i<nums.size(); i++) {
            int n = nums[i];
            if (m.find(n) != m.end() && i - m[n] <= k) {
                return true;
            }
            m[n] = i;
        }
        return false;
    }
};

